package cn.com.xf.web.controller;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import cn.com.xf.common.AbstractBaseController;
import cn.com.xf.common.Constants;
import cn.com.xf.common.StringUtil;
import cn.com.xf.domain.CheckDetail;
import cn.com.xf.domain.TblCheckData;
import cn.com.xf.domain.TblCheckLeave;
import cn.com.xf.domain.TblCheckMend;
import cn.com.xf.service.CompanyService;
import cn.com.xf.service.DataImportService;
import cn.com.xf.service.DataService;
import cn.com.xf.service.LeaveService;
import cn.com.xf.service.MendService;
import cn.com.xf.utils.ATest;
import cn.com.xf.utils.DateUtils;
import cn.com.xf.web.PageModel;
import cn.com.xf.web.form.CheckData;
import cn.com.xf.web.form.CheckDataApi;
import cn.com.xf.web.form.CheckDataForm;
import net.sf.json.JSONArray;


/**
 * 考勤原始数据管理
 *
 */
@Controller
@RequestMapping("/check")
public class CheckDataController extends AbstractBaseController {
	Log log = LogFactory.getLog(CheckDataController.class);
	@Autowired
	private DataService dataService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private LeaveService leaveService;
	@Autowired
	private MendService mendService;
	
	
	private final static String  check_key = "{C0348565-DF02-E1F7-0898-AE78D8402E9B}";
	
	@RequestMapping(value = "/checkSync", method = RequestMethod.POST )
	@ResponseBody
	public void checkSync(HttpServletRequest request, HttpServletResponse response, @RequestBody String body)
			throws Exception {
		request.setCharacterEncoding("utf-8");
		String result = null;
		Object[] data = {};
		net.sf.json.JSONObject josnBody = net.sf.json.JSONObject.fromObject(body);
		String body_sign = josnBody.get("sign")+"";
		String body_data = josnBody.get("data")+"";
		if(!body_sign.equals(ATest.getMd5Sign(check_key+body_data))){
			System.out.println("sign错误");
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("status", "1");
			map.put("error", "接收端sign有误");
			map.put("data",data);
			map.put("sign", ATest.getMd5Sign(check_key+data));
			result = JSONObject.toJSONString(map);
			response.setCharacterEncoding("UTF-8");
			response.getWriter().println(result);
		}else{
			Map<String,Object> resultMap = new HashMap<>();
			resultMap.put("status", "0");
			resultMap.put("error", "");
			List<Map<String,Object>> list = new ArrayList<>();
			List<TblCheckData> listCheck = new ArrayList<>();
			JSONArray arr_data = JSONArray.fromObject(body_data);
			for (int i = 0; i < arr_data.size(); i++) {
				Map<String,Object> map = new HashMap<>();
				TblCheckData tcd = new TblCheckData();
				net.sf.json.JSONObject jsonObj = arr_data.getJSONObject(i);
				tcd.setUserid(jsonObj.getString("userid"));
				tcd.setSiteid(jsonObj.getString("siteid"));
				tcd.setEntersite(jsonObj.getString("siteid"));
				tcd.setCheckdate(DateUtils.parseDate(jsonObj.getString("checkdate")));
				tcd.setChecktime(DateUtils.parseDatetime(jsonObj.getString("checktime")));
				tcd.setDeviceid(jsonObj.get("deviceid")+"");
				tcd.setEnteruser("checkSync");
				tcd.setEntertime(new Date());
				tcd.setType((short) 0);
				listCheck.add(tcd);
				String checkid = jsonObj.getString("checkid");
				map.put("checkid", checkid);
				map.put("sta", "OK");
				map.put("err", "");
				list.add(map);				
			}
			try {
				dataService.insertBatch(listCheck);				
			} catch (Exception e) {
				log.error("考勤同步功能不能插入数据库："+e.getMessage());
				resultMap.put("error", "考勤同步数据不能插入数据库失败");
				resultMap.put("status", "1");
			}finally {
			}
			String resultdata = JSONArray.fromObject(list).toString();
			resultMap.put("data", resultdata);
			result = JSONObject.toJSONString(resultMap);
			response.setCharacterEncoding("UTF-8");
			response.getWriter().println(result);
		}
		
		
	}
	
	@RequestMapping("/addData")
	public ModelAndView addData(HttpServletRequest request, HttpServletResponse response, CheckDataForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/add_data", Constants.FORM_COMMAND_KEY, form);
		mv.addObject("defaultSiteid", getDefaultSiteid());
		return mv;
	}
	
	@RequestMapping("/doAddData")
	public ModelAndView doAddData(HttpServletRequest request, HttpServletResponse response, @Valid CheckDataForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/check/add_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		if(!isSiteId(form.getSiteid())) {
			FieldError e = new FieldError("", "siteid", "所属公司不合法");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		MultipartFile file = form.getData();
		if (!file.isEmpty()) {
			String className = "cn.com.xf.service.impl.DataImportService"+form.getDevice()+"Impl";
			Class<?> c = Class.forName(className);
			DataImportService importService = (DataImportService) c.newInstance();
			importService.importCheckData(file, form.getSiteid(), form.getEntersite(), form.getAdduser());
			mv.addObject("status", "SUCCESS");
		}
		return mv;
	}
	
	@RequestMapping("/dataList")
	public ModelAndView dataList(HttpServletRequest request, HttpServletResponse response, CheckDataForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/data_list", Constants.FORM_COMMAND_KEY, form);
		String siteid = form.getSiteid();
		String userid = StringUtil.StringFilter(form.getUserid());
		String deptid = StringUtil.StringFilter(form.getDeptid()!=null && form.getDeptid().equals("D999")?"":form.getDeptid());
		String year_Month = StringUtil.StringFilter(form.getYear_month());
		if (siteid.equals("") || !isSiteId(siteid)) {
			siteid = getDefaultSiteid();
		}
		form.setSiteid(siteid);
		form.setUserid(userid);
		form.setDeptid(deptid);
		form.setYear_month(year_Month);
		int count = dataService.selectDataCount(year_Month, siteid, deptid, userid);
		if (count == 0)
			return mv;

		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, 30, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();
		List<TblCheckData> list = dataService.selectData(begin, pageSize, year_Month, siteid,deptid, userid);
		mv.addObject("list", list);
		return mv;
	}	

	@RequestMapping("/dataSummaryList")
	public ModelAndView dataSummaryList(HttpServletRequest request, HttpServletResponse response, CheckDataForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/datasummary_list", Constants.FORM_COMMAND_KEY, form);
		String siteid = StringUtil.StringFilter(form.getSiteid());
		String userid = StringUtil.StringFilter(form.getUserid());
		String deptid = StringUtil.StringFilter(form.getDeptid());
		String deviceid = StringUtil.StringFilter(form.getDeviceid());
		String startdateString = StringUtil.StringFilter(form.getStartdate());
		String enddateString = StringUtil.StringFilter(form.getEnddate());
		if (siteid.equals("") || !isSiteId(siteid)) {
			siteid = getDefaultSiteid();
		}
		form.setSiteid(siteid);
		form.setUserid(userid);
		form.setDeptid(deptid);
		form.setDeviceid(deviceid);
		form.setStartdate(startdateString);
		form.setEnddate(enddateString);
		Date startdate = null, enddate = null;
		if (!startdateString.equals("")) {
			startdate = DateUtils.parseDate(startdateString);
		}
		if (!enddateString.equals("")) {
			enddate = DateUtils.parseDate(enddateString);
		}	
		int count = dataService.selectDataSummaryCount(userid, siteid, deptid, startdate, enddate, deviceid);
		if (count == 0)
			return mv;

		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();
		List<TblCheckData> list = dataService.selectDataSummary(begin, pageSize, userid, siteid, deptid, startdate, enddate, deviceid);
		Map<String, Object> map = companyService.getDetps();
		for (TblCheckData data: list) {
			if (data.getDeptid() == null) {
				data.setDeptname("");
			} else {
				data.setDeptname(map.get(data.getDeptid())+"");
			}
		}
		mv.addObject("list", list);
		return mv;
	}	

	
	@RequestMapping("/dataUserList")
	public ModelAndView userData(HttpServletRequest request, HttpServletResponse response, CheckDataForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/datauser_list", Constants.FORM_COMMAND_KEY, form);
		String userid = StringUtil.StringFilter(form.getUserid());
		String deviceid = StringUtil.StringFilter(form.getDeviceid());
		String startdateString = StringUtil.StringFilter(form.getStartdate());
		String enddateString = StringUtil.StringFilter(form.getEnddate());
		form.setUserid(userid);
		form.setDeviceid(deviceid);
		form.setStartdate(startdateString);
		form.setEnddate(enddateString);
		Date startdate = null, enddate = null;
		if (!startdateString.equals("")) {
			startdate = DateUtils.parseDate(startdateString);
		}
		if (!enddateString.equals("")) {
			enddate = DateUtils.parseDate(enddateString);
		}	
		List<TblCheckData> list = dataService.selectUser(userid, deviceid, startdate, enddate);
		Map<String, Object> map = companyService.getDetps();
		for (TblCheckData data: list) {
			if (data.getDeptid() == null) {
				data.setDeptname("");
			} else {
				data.setDeptname(map.get(data.getDeptid())+"");
			}
		}
		List<CheckDetail> detailList = new ArrayList<CheckDetail>();
		Map<Date, List<TblCheckData>> allMap = new HashMap<Date, List<TblCheckData>>();
		for (TblCheckData d: list) {
			if (allMap.containsKey(d.getCheckdate())) {
				List<TblCheckData> dList = allMap.get(d.getCheckdate());
				dList.add(d);
			} else {
				List<TblCheckData> dList = new ArrayList<TblCheckData>();
				dList.add(d);
				allMap.put(d.getCheckdate(), dList);
			}
		}
		
		for (Map.Entry<Date, List<TblCheckData>> m: allMap.entrySet()) {
			List<TblCheckData> dList = m.getValue();
			Collections.sort(dList, new Comparator<TblCheckData>() {
				@Override
				public int compare(TblCheckData o1, TblCheckData o2) {
					return o1.getChecktime().compareTo(o2.getChecktime());
				}
			});
			CheckDetail detail = new CheckDetail();
			for (int i = 0; i < dList.size(); i++) {
				TblCheckData data = dList.get(i);
				detail.setCheckdate(data.getCheckdate());
				detail.setUserid(data.getUserid());
				detail.setUsername(data.getUsername());
				detail.setDeptname(data.getDeptname());
				detail.setSitename(data.getSitename());
				switch (i+1) {
				case 1:
					detail.setChecktime1(data.getChecktime());
					break;
				case 2:
					detail.setChecktime2(data.getChecktime());
					break;
				case 3:
					detail.setChecktime3(data.getChecktime());
					break;
				case 4:
					detail.setChecktime4(data.getChecktime());
					break;
				case 5:
					detail.setChecktime5(data.getChecktime());
					break;
				case 6:
					detail.setChecktime6(data.getChecktime());
					break;
				}
			}
			detailList.add(detail);
		}
		
		Collections.sort(detailList, new Comparator<CheckDetail>() {

			@Override
			public int compare(CheckDetail o1, CheckDetail o2) {
				return o1.getCheckdate().compareTo(o2.getCheckdate());
			}
		});
		
		mv.addObject("list", detailList);
		return mv;
	}
	
	
	
	@RequestMapping(value="/api/data", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> insertFromJson(@RequestBody String body ) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		System.out.println("body="+body);
		CheckDataApi api = JSON.parseObject(body, CheckDataApi.class);
		List<CheckData> list = api.getData();
		List<TblCheckData> dataList = new ArrayList<TblCheckData>();
		if (list != null) {
			for (CheckData d : list) {
				try {
					TblCheckData data = new TblCheckData();
					data.setSiteid(api.getSiteid());
					data.setEntersite(api.getEntersite());
					data.setEnteruser(api.getEnteruser());
					data.setUserid(d.getUserid());
					data.setType((short) d.getType());
					Date checktime = DateUtils.parseDatetime(d.getChecktime());
					Date checkdate = DateUtils.parseDate(d.getChecktime());
					data.setCheckdate(checkdate);
					data.setChecktime(checktime);
					data.setEntertime(new Date());
					dataList.add(data);
				} catch (ParseException e) {
					e.printStackTrace();
				}

			}
		}
		boolean result = false;
		int count = dataService.insertBatch(dataList);
		if (count < 0) {
			result = false;
		} else {
			result = true;
		}
		resultMap.put("result", result);
		return resultMap;
	}
		
	@RequestMapping("/checkExport")
	public void checkExport(HttpServletRequest request, HttpServletResponse response, CheckDataForm form)
			throws Exception {
		String siteid = form.getSiteid();
		String userid = StringUtil.StringFilter(form.getUserid());
		String deptid = StringUtil.StringFilter(form.getDeptid());
		String sitename = form.getSitename();
		String deptname = StringUtil.StringFilter(form.getDeptname());
		String year_Month = StringUtil.StringFilter(form.getYear_month());
		List<TblCheckData> checkList = dataService.selectExport(year_Month, siteid, deptid!=null && deptid.equals("D999")?"":deptid, userid);
		List<TblCheckMend> mendList = mendService.selectExport(year_Month, siteid, deptid!=null && deptid.equals("D999")?"":deptid, userid);
		List<TblCheckLeave> leaveList = leaveService.selectExport(year_Month, siteid, deptid!=null && deptid.equals("D999")?"":deptid, userid);
		String sheetName = year_Month.replaceAll("-", "年")+"月"+sitename+deptname+"考勤全记录";
		String[] title= {"工号","姓名","所属公司","部门","职位","考勤日期","星期","考勤时间1","考勤时间2","考勤时间3",
				"考勤时间4","考勤时间5","考勤时间6","补卡原因","请假开始时间","请假结束时间","请假类型","请假原因"};
		// 1.创建一个workbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
	    // 2.在workbook中添加一个sheet，对应Excel中的一个sheet
	    HSSFSheet sheet = wb.createSheet(sheetName);
	    // 3.在sheet中添加表头第0行，老版本poi对excel行数列数有限制short
	    //锁定第一行
	    sheet.createFreezePane( 0, 1, 0, 1 );
	    HSSFRow row = sheet.createRow((int) 0);
	    // 4.创建单元格，设置值表头，设置表头居中
	    HSSFCellStyle style = wb.createCellStyle();
	    // 居中格式
	    //style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	    for (int i = 0; i < title.length; i++) {    
            HSSFCell cell = row.createCell(i);    
            cell.setCellValue(title[i]);    
            //cell.setCellStyle(style);    
            sheet.setColumnWidth(i, 5*2*256);
        }
	    for (int i = 0; i < checkList.size(); i++) {
            row = sheet.createRow(i + 1);
            TblCheckData tcd = checkList.get(i); 
            row.createCell(0).setCellValue(tcd.getUserid());
            row.createCell(1).setCellValue(tcd.getUsername());
            row.createCell(2).setCellValue(tcd.getSitename());
            row.createCell(3).setCellValue(tcd.getDeptname()!=null?tcd.getDeptname():"");
            row.createCell(4).setCellValue(tcd.getPostname()!=null?tcd.getPostname():"");
            String checkdate = DateUtils.formatDate(tcd.getCheckdate());
            row.createCell(5).setCellValue(checkdate);
            row.createCell(6).setCellValue(tcd.getWeek());
        	String checkTimesStr = tcd.getChecktimes();
        	List<String> times = new ArrayList<>();
        	if(checkTimesStr != null && !checkTimesStr.equals("")){        		
        		times = getCheckTimes(checkdate, checkTimesStr);
        		if(mendList != null && mendList.size() >0){
        			List<String> mendtimes = new ArrayList<>();
        			String mendReason="";
        			for (TblCheckMend mend : mendList) {
        				String menddate = DateUtils.formatDate(mend.getCheckdate());
    					if(checkdate.equals(menddate) && tcd.getUserid().equals(mend.getUserid())){
    						String time1 = null;
    						String time2 = null;
    						String time3 = null;
    						if(mend.getTime1() != null){
    							time1 = DateUtils.formatTime(mend.getTime1());
    							times.add(time1);
    							mendtimes.add(time1);
    						}
    						if(mend.getTime2() != null){
    							time2 = DateUtils.formatTime(mend.getTime2());
    							times.add(time2);
    							mendtimes.add(time2);
    						}
    						if(mend.getTime3() != null){
    							time3 = DateUtils.formatTime(mend.getTime3());
    							times.add(time3);
    							mendtimes.add(time3);
    						}
    						if(mendReason.equals("")){
    							mendReason = mend.getReason()!=null?mend.getReason():"";
    						}else{
    							mendReason += mend.getReason()!=null?","+mend.getReason():"";
    						}
    					}
    				}
        			Collections.sort(times);
        			if(mendtimes != null && mendtimes.size() >0){
        				style.setFillPattern(CellStyle.SOLID_FOREGROUND);
                		style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
    					switch (times.size()) {
    					case 1:
    						style.setFillPattern(CellStyle.SOLID_FOREGROUND);
                    		style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
							row.createCell(7).setCellValue(times.get(0));
							for (String mendtime : mendtimes) {
								if(times.get(0).equals(mendtime)){
									row.getCell(7).setCellStyle(style);
								}
							}
							break;
						case 2:	
							row.createCell(7).setCellValue(times.get(0));
							row.createCell(8).setCellValue(times.get(1));
							for (String mendtime : mendtimes) {
								if(times.get(0).equals(mendtime)){
									row.getCell(7).setCellStyle(style);
								}else if(times.get(1).equals(mendtime)){
									row.getCell(8).setCellStyle(style);
								}
							}
							break;
						case 3:	
							row.createCell(7).setCellValue(times.get(0));
							row.createCell(8).setCellValue(times.get(1));
							row.createCell(9).setCellValue(times.get(2));
							for (String mendtime : mendtimes) {
								if(times.get(0).equals(mendtime)){
									row.getCell(7).setCellStyle(style);
								}else if(times.get(1).equals(mendtime)){
									row.getCell(8).setCellStyle(style);
								}else if(times.get(2).equals(mendtime)){
									row.getCell(9).setCellStyle(style);
								}
							}
							break;
						case 4:	
							row.createCell(7).setCellValue(times.get(0));
							row.createCell(8).setCellValue(times.get(1));
							row.createCell(9).setCellValue(times.get(2));
							row.createCell(10).setCellValue(times.get(3));
							for (String mendtime : mendtimes) {
								if(times.get(0).equals(mendtime)){
									row.getCell(7).setCellStyle(style);
								}else if(times.get(1).equals(mendtime)){
									row.getCell(8).setCellStyle(style);
								}else if(times.get(2).equals(mendtime)){
									row.getCell(9).setCellStyle(style);
								}else if(times.get(3).equals(mendtime)){
									row.getCell(10).setCellStyle(style);
								}
							}
							break;
						case 5:	
							row.createCell(7).setCellValue(times.get(0));
							row.createCell(8).setCellValue(times.get(1));
							row.createCell(9).setCellValue(times.get(2));
							row.createCell(10).setCellValue(times.get(3));
							row.createCell(11).setCellValue(times.get(4));
							for (String mendtime : mendtimes) {
								if(times.get(0).equals(mendtime)){
									row.getCell(7).setCellStyle(style);
								}else if(times.get(1).equals(mendtime)){
									row.getCell(8).setCellStyle(style);
								}else if(times.get(2).equals(mendtime)){
									row.getCell(9).setCellStyle(style);
								}else if(times.get(3).equals(mendtime)){
									row.getCell(10).setCellStyle(style);
								}else if(times.get(4).equals(mendtime)){
									row.getCell(11).setCellStyle(style);
								}
							}
							break;
						case 6:	
							row.createCell(7).setCellValue(times.get(0));
							row.createCell(8).setCellValue(times.get(1));
							row.createCell(9).setCellValue(times.get(2));
							row.createCell(10).setCellValue(times.get(3));
							row.createCell(11).setCellValue(times.get(4));
							row.createCell(12).setCellValue(times.get(5));
							for (String mendtime : mendtimes) {
								if(times.get(0).equals(mendtime)){
									row.getCell(7).setCellStyle(style);
								}else if(times.get(1).equals(mendtime)){
									row.getCell(8).setCellStyle(style);
								}else if(times.get(2).equals(mendtime)){
									row.getCell(9).setCellStyle(style);
								}else if(times.get(3).equals(mendtime)){
									row.getCell(10).setCellStyle(style);
								}else if(times.get(4).equals(mendtime)){
									row.getCell(11).setCellStyle(style);
								}else if(times.get(5).equals(mendtime)){
									row.getCell(12).setCellStyle(style);
								}
							}
							break;
    					}
        				row.createCell(13).setCellValue(mendReason);
						row.getCell(13).setCellStyle(style);
        			}else{
						if(times != null){
	        				switch (times.size()) {
							case 1:	
								row.createCell(7).setCellValue(times.get(0));
								break;
							case 2:	
								row.createCell(7).setCellValue(times.get(0));
								row.createCell(8).setCellValue(times.get(1));
								break;
							case 3:	
								row.createCell(7).setCellValue(times.get(0));
								row.createCell(8).setCellValue(times.get(1));
								row.createCell(9).setCellValue(times.get(2));
								break;
							case 4:	
								row.createCell(7).setCellValue(times.get(0));
								row.createCell(8).setCellValue(times.get(1));
								row.createCell(9).setCellValue(times.get(2));
								row.createCell(10).setCellValue(times.get(3));
								break;
							case 5:	
								row.createCell(7).setCellValue(times.get(0));
								row.createCell(8).setCellValue(times.get(1));
								row.createCell(9).setCellValue(times.get(2));
								row.createCell(10).setCellValue(times.get(3));
								row.createCell(11).setCellValue(times.get(4));
								break;
							case 6:	
								row.createCell(7).setCellValue(times.get(0));
								row.createCell(8).setCellValue(times.get(1));
								row.createCell(9).setCellValue(times.get(2));
								row.createCell(10).setCellValue(times.get(3));
								row.createCell(11).setCellValue(times.get(4));
								row.createCell(12).setCellValue(times.get(5));
								break;
	        				}
	        			}
					}    						
        		}else{
        			if(times != null){
        				switch (times.size()) {
						case 1:	
							row.createCell(7).setCellValue(times.get(0));
							break;
						case 2:	
							row.createCell(7).setCellValue(times.get(0));
							row.createCell(8).setCellValue(times.get(1));
							break;
						case 3:	
							row.createCell(7).setCellValue(times.get(0));
							row.createCell(8).setCellValue(times.get(1));
							row.createCell(9).setCellValue(times.get(2));
							break;
						case 4:	
							row.createCell(7).setCellValue(times.get(0));
							row.createCell(8).setCellValue(times.get(1));
							row.createCell(9).setCellValue(times.get(2));
							row.createCell(10).setCellValue(times.get(3));
							break;
						case 5:	
							row.createCell(7).setCellValue(times.get(0));
							row.createCell(8).setCellValue(times.get(1));
							row.createCell(9).setCellValue(times.get(2));
							row.createCell(10).setCellValue(times.get(3));
							row.createCell(11).setCellValue(times.get(4));
							break;
						case 6:	
							row.createCell(7).setCellValue(times.get(0));
							row.createCell(8).setCellValue(times.get(1));
							row.createCell(9).setCellValue(times.get(2));
							row.createCell(10).setCellValue(times.get(3));
							row.createCell(11).setCellValue(times.get(4));
							row.createCell(12).setCellValue(times.get(5));
							break;
        				}
        			}
        		}
        	}else{
        		if(mendList != null && mendList.size() >0){
        			String mendReason="";
        			for (TblCheckMend mend : mendList) {
        				String menddate = DateUtils.formatDate(mend.getCheckdate());
    					if(checkdate.equals(menddate) && tcd.getUserid().equals(mend.getUserid())){
    						String time1 = null;
    						String time2 = null;
    						String time3 = null;
    						if(mend.getTime1() != null){
    							time1 = DateUtils.formatTime(mend.getTime1());
    							times.add(time1);
    						}
    						if(mend.getTime2() != null){
    							time2 = DateUtils.formatTime(mend.getTime2());
    							times.add(time2);
    						}
    						if(mend.getTime3() != null){
    							time3 = DateUtils.formatTime(mend.getTime3());
    							times.add(time3);
    						}
    						if(mendReason.equals("")){
    							mendReason = mend.getReason()!=null?mend.getReason():"";
    						}else{
    							mendReason += mend.getReason()!=null?","+mend.getReason():"";
    						}
    					}
    				}
        			
        			Collections.sort(times);
					if(times != null){
						switch (times.size()) {
						case 1:	
							row.createCell(7).setCellValue(times.get(0));
							row.getCell(7).setCellStyle(style);
							break;
						case 2:	
							row.createCell(7).setCellValue(times.get(0));
							row.createCell(8).setCellValue(times.get(1));
							row.getCell(7).setCellStyle(style);
							row.getCell(8).setCellStyle(style);
							break;
						case 3:	
							row.createCell(7).setCellValue(times.get(0));
							row.createCell(8).setCellValue(times.get(1));
							row.createCell(9).setCellValue(times.get(2));
							row.getCell(7).setCellStyle(style);
							row.getCell(8).setCellStyle(style);
							row.getCell(9).setCellStyle(style);
							break;
						case 4:	
							row.createCell(7).setCellValue(times.get(0));
							row.createCell(8).setCellValue(times.get(1));
							row.createCell(9).setCellValue(times.get(2));
							row.createCell(10).setCellValue(times.get(3));
							row.getCell(7).setCellStyle(style);
							row.getCell(8).setCellStyle(style);
							row.getCell(9).setCellStyle(style);
							row.getCell(10).setCellStyle(style);
							break;
						case 5:	
							row.createCell(7).setCellValue(times.get(0));
							row.createCell(8).setCellValue(times.get(1));
							row.createCell(9).setCellValue(times.get(2));
							row.createCell(10).setCellValue(times.get(3));
							row.createCell(11).setCellValue(times.get(4));
							row.getCell(7).setCellStyle(style);
							row.getCell(8).setCellStyle(style);
							row.getCell(9).setCellStyle(style);
							row.getCell(10).setCellStyle(style);
							row.getCell(11).setCellStyle(style);
							break;
						case 6:	
							row.createCell(7).setCellValue(times.get(0));
							row.createCell(8).setCellValue(times.get(1));
							row.createCell(9).setCellValue(times.get(2));
							row.createCell(10).setCellValue(times.get(3));
							row.createCell(11).setCellValue(times.get(4));
							row.createCell(12).setCellValue(times.get(5));
							row.getCell(7).setCellStyle(style);
							row.getCell(8).setCellStyle(style);
							row.getCell(9).setCellStyle(style);
							row.getCell(10).setCellStyle(style);
							row.getCell(11).setCellStyle(style);
							row.getCell(12).setCellStyle(style);
							break;
						}
					}
					if(!mendReason.equals("")){
						row.createCell(13).setCellValue(mendReason);
						row.getCell(13).setCellStyle(style);
					}
        		}
        	}        	
            if(leaveList != null && leaveList.size()>0){
            	for (TblCheckLeave leave : leaveList) {
            		String leavedate = DateUtils.formatDate(leave.getStartdate());
            		if(leavedate.equals(checkdate) && tcd.getUserid().equals(leave.getUserid())){
                    	style.setFillPattern(CellStyle.SOLID_FOREGROUND);
                    	style.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
                    	row.createCell(14).setCellValue(leave.getStartdate() == null?"":DateUtils.formatDatetime(leave.getStartdate()));
                        row.createCell(15).setCellValue(leave.getEnddate() == null?"":DateUtils.formatDatetime(leave.getEnddate()));
                        row.createCell(16).setCellValue(leave.getType() == null?"":leave.getType());
                        row.createCell(17).setCellValue(leave.getReason()== null?"":leave.getReason());
                        row.getCell(14).setCellStyle(style);
                        row.getCell(15).setCellStyle(style);
                        row.getCell(16).setCellStyle(style);
                        row.getCell(17).setCellStyle(style);
                        break;
            		}            		
            	}
            }            
        }
	    response.setContentType("application/vnd.ms-excel;charset=utf-8");
	    response.setHeader("Content-Disposition", "attachment;filename="
	            + new String((sheetName + ".xls").getBytes(), "iso-8859-1"));
	    OutputStream ouputStream = response.getOutputStream();    
        wb.write(ouputStream);    
        ouputStream.flush();    
        ouputStream.close();
	}
	public static List<String> getCheckTimes(String checkDate ,String checkTimes) throws ParseException{
		Long time30 = 30*60*1000L;
		String [] str = checkTimes.split(",");
		Arrays.sort(str);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		List<String> list = new ArrayList<>();
		for(String t : str){    
			list.add(t); 
		}
		for (int i = list.size() - 1; i >= 1; i--) {
			Long time0 = sdf.parse(checkDate+" "+list.get(i)).getTime();
			Long time1 = sdf.parse(checkDate+" "+list.get(i-1)).getTime();
			if(time0-time1<time30){
				list.remove(i-1);
			}
		}
		return list;
	}
	
	/**
	 * 查询总考勤报表信息
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/checkDatailReportList")
	public ModelAndView checkDatailReport(HttpServletRequest request, HttpServletResponse response, CheckDataForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/check_detail_report", Constants.FORM_COMMAND_KEY, form);
		String siteid = StringUtil.StringFilter(form.getSiteid());
		String userid = StringUtil.StringFilter(form.getUserid());
		String deptid = StringUtil.StringFilter(form.getDeptid()!=null && form.getDeptid().equals("D999")?"":form.getDeptid());
		String year_Month = StringUtil.StringFilter(form.getYear_month());
		if (siteid.equals("") || !isSiteId(siteid)) {
			siteid = getDefaultSiteid();
		}
		form.setSiteid(siteid);
		form.setUserid(userid);
		form.setDeptid(deptid);
		form.setYear_month(year_Month);
		int count = dataService.selectDatailReportListCount(year_Month, siteid, deptid);
		if (count == 0)
			return mv;

		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, 30, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();
		List<TblCheckData> list = dataService.selectDatailReportList(begin, pageSize, year_Month, siteid,deptid);
//		if(deptid !=null && deptid.equals("")) {
//			int allcount = 0;
//			int kqcount = 0;
//			String sitename = null;
//			for (TblCheckData tblCheckData : list) {
//				sitename = tblCheckData.getSitename();
//				allcount =allcount + Integer.valueOf(tblCheckData.getAllcount()!=null?tblCheckData.getAllcount():"0");
//				kqcount =kqcount + Integer.valueOf(tblCheckData.getKqcount()!=null?tblCheckData.getKqcount():"0");
//			}
//			TblCheckData tblCheckData = new TblCheckData();
//			tblCheckData.setSitename(sitename);
//			tblCheckData.setDeptname("站点统计");
//			tblCheckData.setAllcount(String.valueOf(allcount));
//			tblCheckData.setKqcount(String.valueOf(kqcount));
//			BigDecimal b = new BigDecimal(allcount/kqcount);
//			tblCheckData.setCheckpro(b.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
//			list.add(tblCheckData);
//		}
		mv.addObject("list", list);
		return mv;
	}
	
	@RequestMapping("/checkSitesReportList")
	public ModelAndView getSitesCheckReport(HttpServletRequest request, HttpServletResponse response, CheckDataForm form) throws Exception {
		ModelAndView mv = new ModelAndView("/check/check_sites_report",Constants.FORM_COMMAND_KEY, form);
		String siteid = StringUtil.StringFilter(form.getSiteid());
		String year_Month = StringUtil.StringFilter(form.getYear_month());
		form.setSiteid(siteid);
		form.setYear_month(year_Month);
		Map<String, Object> map = dataService.getSitesCheckReport(siteid, year_Month);
		List<Object> list = (List<Object>) map.get("result");
		mv.addObject("list", list);
		return mv;
	}
}
